package unei;

import org.junit.Test;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.concurrent.*;

/**
 * Created by Eilir on 2015/12/31.
 */
public class WriteFile {

    @Test
    public void testPoolFile() throws ExecutionException, InterruptedException {
        ExecutorService executorService = Executors.newCachedThreadPool();
        long start = System.currentTimeMillis();
        Future future = executorService.submit(new Task());
        if(future.get()!=null)
            System.out.println("耗时："+(System.currentTimeMillis() - start)+" ms");
    }

    @Test
    public void testSingleFile() throws IOException {
        int count = 0;
        File target = new File("E:/test2.txt");
        FileWriter fw = new FileWriter(target,true);
        long start = System.currentTimeMillis();
        while(count++<1024){
            fw.write(count+"\r\n");
        }
        System.out.println("耗时："+(System.currentTimeMillis() - start)+" ms");
    }

    class Task implements Callable {

        @Override
        public Object call() throws Exception {
            File target = new File("E:/TEST.txt");
            if (!target.exists()) {
                target.createNewFile();
            }
            FileWriter fw = new FileWriter(target.getName(), true);
            BufferedWriter bufferWritter = new BufferedWriter(fw);

            int count = 0;
            while (count < 1024) {
                bufferWritter.write(count + "\r\n");
                count++;
            }
            bufferWritter.flush();
            bufferWritter.close();
            return count <= 1024;
        }
    }}
